<template>
    <div class="files">
        <div v-if="innerFiles.length === 0" style="font-size: 14px;margin-left: 20px;">暂无文件~</div>
        <div v-for="(item, index) in innerFiles" :key="index" class="file-item">
            <i class="el-icon-document"></i>
            <span class="name" @click="handleDownload(item)">{{ item.name }}</span>
            <span class="text-blue-light" @click="handleDownload(item)">下载</span>
        </div>
    </div>
</template>

<script>
import axios from 'axios'
export default {
    name: 'FileList',
    props: {
        files: {
            type: [Array, String],
            default: () => []
        }
    },
    data() {
        return {
            innerFiles: []
        }
    },
    watch: {
        files: {
            handler: function(val) {
                if (val) {
                    if (Array.isArray(val)) {
                        this.innerFiles = val
                    } else {
                        try {
                            this.innerFiles = JSON.parse(val)
                        } catch {
                            this.innerFiles = []
                            throw new Error('文件数据类型错误')
                        }
                    }
                }
            },
            immediate: true,
            // deep: true
        }
    },
    created() {
    },
    methods: {
        downloadFile(item) {
            axios
                .get(item.url, {
                    // 这里设置为blob或者arraybuffer都可以
                    responseType: 'blob'
                    // responseType: 'arraybuffer'
                })
                .then((res) => {
                    this.handleResult(item.name, res.data)
                })
        },
        handleResult(fileName = '附件', blob) {
            const url = URL.createObjectURL(blob) // 传入返回的blob对象
            const a = document.createElement('a')
            a.href = url
            a.download = fileName
            document.body.appendChild(a)
            a.click()
            document.body.removeChild(a)
        },
        handleDownload(data) {
            // 模拟a标签点击下载文件
            const a = document.createElement('a')
            a.href = data.url
            a.download = data.name
            // a标签添加到body中，然后模拟点击，火狐浏览器需要把a标签添加到body中点击才有效，谷歌可以省略appendChild这一步
            document.body.appendChild(a)
            a.click()
            // 把a标签删除，减少dom节点冗余
            document.body.removeChild(a)
        }
    },
}
</script>

<style lang="scss" scoped>
.files {
    font-size: 14px;
    .text-blue-light {
        cursor: pointer;
    }
    .file-item {
        padding: 4px 0;
        display: flex;
        align-items: center;
        .name {
            margin: 0 16px 0 8px;
            cursor: pointer;
        }
        .text-blue-light{
            cursor: pointer;
        }
    }
}
</style>
